package com.bjpowernode.front.controller;

import com.bjpowernode.api.model.User;
import com.bjpowernode.common.constants.RedisKey;
import com.bjpowernode.common.util.CommonUtil;
import com.bjpowernode.front.view.RespResult;
import com.bjpowernode.front.view.invest.RankView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 有关投资的功能
 */
@RestController
@Api(tags = "投资理财产品")
@RequestMapping("/v1/invest")
public class InvestController extends BaseController {

    /*投资排行榜*/
    @GetMapping("/rank")
    @ApiOperation(value = "投资排行榜",notes = "显示投资金额最高的三位到投资排行榜")
    public RespResult showInvestRank(){
        Set<ZSetOperations.TypedTuple<String>> sets = stringRedisTemplate.boundZSetOps(RedisKey.KEY_INVEST_RANK)
                .reverseRangeWithScores(0, 2);
        ArrayList<RankView> rankList = new ArrayList<>();
        //便利set集合
        sets.forEach(temp ->{
            rankList.add(new RankView(CommonUtil.tuoming(temp.getValue()),temp.getScore()));
        });

        return RespResult.ok(rankList);
    }

    /*购买理财产品*/
    @ApiOperation(value = "投资理财产品")
    @PostMapping("/product")
    public RespResult investProduct(
            @RequestHeader("uid") Integer uid,
            @RequestParam("productId") Integer productId,
            @RequestParam("money")BigDecimal money
            ){
        //检查参数
        if ((uid != null && uid >0)
                && (productId != null && productId >0)
                && (money != null && money.intValue() % 100 == 0)&& money.intValue()>= 100){
            int investResult = investService.investProduct(uid,productId,money);
            switch (investResult){
                case 0:
                    return RespResult.fail("投资数据不正确");
                case 1:
                    modifyInvestRank(uid,money);
                    return RespResult.ok("投资成功");
                case 2:
                    return RespResult.fail("资金账号不存在");
                case 3:
                    return RespResult.fail("资金不足");
                case 4:
                    return RespResult.fail("理财产品不存在");
            }
        }
        return RespResult.fail("参数不正确");
    }

    /*更新投资排行榜*/
    private void modifyInvestRank(Integer uid,BigDecimal money){
        User user = userService.queryById(uid);
        if (user != null){
            //更新redis中的投资排行榜
            String key = RedisKey.KEY_INVEST_RANK;
            stringRedisTemplate.boundZSetOps(key).incrementScore(user.getPhone(),money.doubleValue());
        }
    }
}
